package cn.edu.pet.util;

import cn.edu.pet.entity.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

public class PaginationUtil<T> {

    private static final int DEFAULT_PAGE_SIZE = 5;

    public String paginate(List<T> items, int currentPage, int pageSize) {
        int totalItems = items.size();
        int totalPages = (int) Math.ceil((double) totalItems / pageSize);
        currentPage = Math.max(1, Math.min(currentPage, totalPages));

        int startIndex = (currentPage - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, totalItems);

        List<T> sublist = items.subList(startIndex, endIndex);
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(new Page<>(sublist, totalPages, currentPage > 1, currentPage < totalPages));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public String paginate(List<T> items, int currentPage) {
        return paginate(items, currentPage, DEFAULT_PAGE_SIZE);
    }
}
